﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace ProjBackEnd.Common.Helper
{
    public class X509Certificate2Helper
    {
        /// <summary>
        /// 通过证书序列号获取中间证书颁发机构存储区中的证书
        /// </summary>
        /// <param name="serialNumber"></param>
        /// <returns></returns>
        public static X509Certificate2 GetX509Certificate2BySerialNumber(string serialNumber, StoreName storeName, StoreLocation storeLocation)
        {
            //X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);
            X509Store store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
            X509Certificate2Collection collection = store.Certificates;
            X509Certificate2 certificate2 = null;
            foreach (var item in collection)
            {
                if (item.SerialNumber.ToUpper() == serialNumber.ToUpper())
                {
                    certificate2 = item;
                    break;
                }
            }
            return certificate2;
        }
    }
}
